<template>
  <div class="p-2">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['beauty:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['beauty:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['beauty:banner:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            :initial-index="0"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['beauty:banner:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['beauty:banner:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="" align="center" min-width="1" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="bannerFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图标题" maxlength="100" />
        </el-form-item>
        <el-form-item label="轮播图图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Banner">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import ImageUpload from '@/components/ImageUpload/index.vue';
import {
  listBanner,
  getBanner,
  addBanner,
  updateBanner,
  delBanner,
  exportBanner
} from '@/api/beauty/banner';
import type { BannerQuery, BannerVO, BannerForm } from '@/api/beauty/banner';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const loading = ref(true);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const bannerList = ref<BannerVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const bannerFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<BannerQuery>({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  status: undefined
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const form = ref<BannerForm>({
  title: '',
  imageUrl: '',
  sortOrder: 0,
  status: '0',
  remark: undefined
});

const rules = reactive({
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '图片不能为空', trigger: 'blur' }
  ]
});

/** 查询轮播图列表 */
function getList() {
  loading.value = true;
  listBanner(queryParams.value).then((response: any) => {
    bannerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: BannerVO[]) {
  ids.value = selection.map((item) => item.bannerId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 取消按钮 */
function cancel() {
  dialog.visible = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    title: '',
    imageUrl: '',
    sortOrder: 0,
    status: '0',
    remark: undefined
  };
  bannerFormRef.value?.resetFields();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  dialog.visible = true;
  dialog.title = '添加轮播图';
}

/** 修改按钮操作 */
function handleUpdate(row?: BannerVO) {
  reset();
  const bannerId = row?.bannerId || ids.value[0];
  getBanner(bannerId).then((response: any) => {
    form.value = response.data;
    dialog.visible = true;
    dialog.title = '修改轮播图';
  });
}

/** 提交按钮 */
function submitForm() {
  bannerFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.bannerId) {
        updateBanner(form.value).then(() => {
          ElMessage.success('修改成功');
          dialog.visible = false;
          getList();
        });
      } else {
        addBanner(form.value).then(() => {
          ElMessage.success('新增成功');
          dialog.visible = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row?: BannerVO) {
  const bannerIds = row?.bannerId ? [row.bannerId] : ids.value;
  ElMessageBox.confirm('是否确认删除轮播图编号为"' + bannerIds + '"的数据项？')
    .then(() => {
      return delBanner(bannerIds);
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.$download(
    'admin/beauty/banner/export',
    {
      ...queryParams.value
    },
    `banner_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
